package com.mystudy.leetcode.problem.link.p_92;

import com.mystudy.leetcode.base.ListNode;
import com.mystudy.leetcode.base.ListNodeUtils;
import org.junit.Test;

/**
 * @program: infoalgorithm
 * @description: 中等题目:反转链表2
 * @author: zhouzhilong
 * @create: 2019-07-08 10:27
 **/
public class Solution {


    @Test
    public void test() {
        ListNode listNode = ListNodeUtils.generateLinkList(new int[]{1, 2, 3, 4, 5});
        ListNode listNode1 = reverseBetween(listNode, 2, 4);
        ListNodeUtils.show(listNode1);
    }


    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummyHead = new ListNode(-1);
        dummyHead.next = head;
        ListNode prev = dummyHead;
        ListNode cur = head;
        int count = 1;
        while (cur != null) {
            if (count >= m) {
                if (count < n) {
                    ListNode nextTemp = cur.next;
                    cur.next = nextTemp.next;
                    nextTemp.next = prev.next;
                    prev.next = nextTemp;
                } else {
                    break;
                }
            } else {
                prev = prev.next;
                cur = cur.next;
            }

            count++;
        }

        return dummyHead.next;
    }
}
